﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using NLog;
using OddUserManager.Model;
using OddUserManager.Service.IServices;
using OddUserManager.Web.Models;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace OddUserManager.Web.Controllers
{
    public class AppUserController : BaseController
    {
        static Logger log = LogManager.GetCurrentClassLogger();
        private readonly IAppUserService _service;
        private readonly IRoleService _roleService;
        public AppUserController(IAppUserService appUserService, IRoleService roleService)
        {
            _service = appUserService;
            _roleService = roleService;
        }
        // GET: AppUser
        public IActionResult Index()
        {
            JsonData data = new JsonData();
            data.Data = _service.GetAllUserList();
            return View(data);
        }



        public IActionResult GetAllUser()
        {
            JsonData d = new JsonData();
            var list = _service.GetAllUserList();
            IList result = new ArrayList();
            foreach (var i in list)
            {
                result.Add(new { Id = i.Id, Text = i.Name,ColorName=i.ColorName });
            }
            d.Data = result;
            return Json(d);
        }

        public IActionResult GetAllUsers(int startPage, int pageSize)
        {
            var list = _service.GetAllUserList();

            var pageList = list.Skip((startPage - 1) * pageSize).Take(pageSize);
            var roles = _roleService.GetAllList();
            JsonData data = new JsonData();
            data.Data = new 
            {
                AllCount = list.Count,
                PageCount = Math.Ceiling(Convert.ToDecimal(list.Count) / pageSize),
                Data = pageList,
                Roles = roles
            };
            return Json(data);
        }



        public async Task<IActionResult> UpdatePassword(string oldPassword, string newPassword)
        {
            JsonData data = new JsonData();
            try
            {
                
                var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
                if (result.Succeeded)
                {
                    var id = result.Principal.Identity.Name;
                    var user = _service.GetUserById(int.Parse(id));

                    if (user.UPassword == oldPassword)
                    {
                        user.UPassword = newPassword;
                        _service.InsertOrUpdateUser(user);
                    }
                    else
                    {
                        throw new Exception("旧密码错误!");
                    }
                }
                data.Message = "更新成功";
            }
            catch (Exception ex)
            {
                data.Success = false;
                data.Message = ex.Message;
                log.Error(ex, ex.Message);
            }
            return Json(data);
        }

        public async Task<IActionResult> Edit(AppUser dto, string roles)
        {
            JsonData data = new JsonData();
            try
            {
                var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
                if (result.Succeeded)
                {
                    var Id = result.Principal.Identity.Name;
                    dto.CreateUserId = int.Parse(Id);
                }
                var userRoles = new List<UserRoles>();
                if (dto.Id <= 0)
                {
                    dto.CreateTime = DateTime.Now;
                    dto.LastLoginTime = DateTime.Now;
                }
                if (null != roles)
                {
                    foreach (var role in roles.Split(','))
                    {
                        userRoles.Add(new UserRoles() { UserId = dto.Id, RoleId = int.Parse(role) });
                    }
                }

                dto.UserRoles = userRoles;
                var user = _service.InsertOrUpdateUser(dto);
                data.Message = "更新成功";
            }
            catch (Exception ex)
            {
                data.Success = false;
                data.Message = ex.Message;
                log.Error(ex, ex.Message);
            }
            return Json(data);
        }

        public IActionResult DeleteMuti(string ids)
        {
            JsonData data = new JsonData();
            try
            {
                string[] idArray = ids.Split(',');

                List<int> delIds = new List<int>();
                foreach (string id in idArray)
                {
                    delIds.Add(int.Parse(id));
                }

                if (delIds.Contains(6))
                {
                    throw new Exception("不能删除超级管理员!");
                }
                _service.DeleteBatchUsers(delIds);
                
            }
            catch (Exception ex)
            {
                data.Success = false;
                data.Message = ex.Message;
                log.Error(ex, ex.Message);
            }
            return Json(data);
        }
        public IActionResult Delete(int id)
        {
            JsonData data = new JsonData();
            try
            {
                if (id == 1)
                {
                    throw new Exception("不能删除超级管理员!");
                }
                _service.DeleteUserById(id);
            }
            catch (Exception ex)
            {
                data.Success = false;
                data.Message = ex.Message;
                log.Error(ex, ex.Message);
            }
            return Json(data);
        }
        public IActionResult Get(int id)
        {
            JsonData data = new JsonData();
            data.Data = _service.GetUserById(id);
            return Json(data);
        }

    }
}
